package com.cgq.pro.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.cgq.base.action.BaseAction;
import com.cgq.pro.entity.PhotoType;
import com.cgq.pro.entity.Region;
import com.cgq.pro.entity.RegionStatistics;
import com.cgq.pro.service.AttachmentService;
import com.cgq.pro.service.LandService;
import com.cgq.pro.service.PhotoTypeService;
import com.cgq.pro.service.RegionService;
import com.cgq.pro.service.RegionStaticService;
import com.cgq.utils.Constants;
import com.cgq.utils.GlobalContext;
import com.cgq.utils.IdGenerator;

@Controller
public class RegionStatisticsAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	@Autowired
	private RegionStaticService regionStaticService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private PhotoTypeService photoTypeService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private LandService landService;
	
	/** 操作方式：增加(add),删除(delete),修改(modify),详情(detail)*/
	private String viewType;
	private RegionStatistics model;
	/**删除数据的id数组*/
	private String ids;
	/**页面行政区列表*/
	private List<Region> regions;
	private String startDate;
	private String endDate;
	/**统计图表json数据*/
	private JSONArray statisObj;
	/**行政区编号*/
	private String regionId;
	/**照片类型列表*/
	private List<PhotoType> ptypes;
	/**照片列表*/
	private JSONArray photos;
	/**要删除的照片编号*/
	private String photoId;
	/**照片类型编号*/
	private String ptypeid;
	/**经度*/
	private String lon;
	/**纬度*/
	private String lat;
	private Map<Integer, String> useTypes=new HashMap<Integer, String>();
	
	public Map<Integer, String> getUseTypes() {
		return useTypes;
	}
	public void setUseTypes(Map<Integer, String> useTypes) {
		this.useTypes = useTypes;
	}
	public RegionStaticService getRegionStaticService() {
		return regionStaticService;
	}
	public void setRegionStaticService(RegionStaticService regionStaticService) {
		this.regionStaticService = regionStaticService;
	}
	public RegionService getRegionService() {
		return regionService;
	}
	public void setRegionService(RegionService regionService) {
		this.regionService = regionService;
	}
	public String getViewType() {
		return viewType;
	}
	public void setViewType(String viewType) {
		this.viewType = viewType;
	}
	public RegionStatistics getModel() {
		return model;
	}
	public void setModel(RegionStatistics model) {
		this.model = model;
	}
	public String getIds() {
		return ids;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}
	public List<Region> getRegions() {
		return regions;
	}
	public void setRegions(List<Region> regions) {
		this.regions = regions;
	}
	public String getStartDate() {
		return startDate;
	}
	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}
	public String getEndDate() {
		return endDate;
	}
	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}
	public JSONArray getStatisObj() {
		return statisObj;
	}
	public void setStatisObj(JSONArray statisObj) {
		this.statisObj = statisObj;
	}
	public String getRegionId() {
		return regionId;
	}
	public void setRegionId(String regionId) {
		this.regionId = regionId;
	}
	public List<PhotoType> getPtypes() {
		return ptypes;
	}
	public void setPtypes(List<PhotoType> ptypes) {
		this.ptypes = ptypes;
	}
	public JSONArray getPhotos() {
		return photos;
	}
	public void setPhotos(JSONArray photos) {
		this.photos = photos;
	}
	public String getPhotoId() {
		return photoId;
	}
	public void setPhotoId(String photoId) {
		this.photoId = photoId;
	}
	public String getPtypeid() {
		return ptypeid;
	}
	public void setPtypeid(String ptypeid) {
		this.ptypeid = ptypeid;
	}
	public String getLon() {
		return lon;
	}
	public void setLon(String lon) {
		this.lon = lon;
	}
	public String getLat() {
		return lat;
	}
	public void setLat(String lat) {
		this.lat = lat;
	}
	/**
	 * 调转到列表界面
	 * @return
	 */
	public String toList(){
		regions=regionService.findAll();
		permissionId=getCurrentUser().getPerId().getPerFlag();
		return GlobalContext.RESULT_LIST_UI;
	}
	
	/**
	 * 跳转到增删改界面*/
	public String toForm(){
		useTypes=landService.getLandUseType();
		if(GlobalContext.RESULT_ADD.equals(viewType)){
			model=new RegionStatistics();
		}else{
			model=regionStaticService.find(model.getId());
		}
		return GlobalContext.RESULT_FORM_UI;
	}
	/**跳转到相册*/
	public String toPhotoview(){
		ptypes=photoTypeService.findByType(Constants.PHOTOTYPE_REGION);
		photos=JSONArray.fromObject(attachmentService.findByBusinessIdAndTypeAndId(ptypes.get(0).getId(), Constants.BUSINESSTYPE_REGION,model.getId()));
		return GlobalContext.RESULT_PHOTO_UI;
	}
	/**刷新相册列表*/
	public String toRefreshphotoview(){
		photos=JSONArray.fromObject(attachmentService.findByBusinessIdAndTypeAndId(ptypeid, Constants.BUSINESSTYPE_REGION,model.getId())) ;
		return GlobalContext.RESULT_PHOTO_REFRESH;
	}
	/**删除照片（包括附件表里面的数据和照片）*/
	public void deleteAndPhoto(){
		if(attachmentService.deleteAndPhoto(photoId,getRootPath())){
			ajaxDoneSuccess("删除照片成功");
		}else{
			ajaxDoneError("删除照片失败");
		}
	}
	/**
	 * 保存数据
	 * @throws Exception 
	 */
	public void save() throws Exception{
		try {
			model.setRegionId(regionService.find(regionId));
			model.setLon(lon);
			model.setLat(lat);
			if(GlobalContext.RESULT_ADD.equals(viewType))//保存
			{
				model.setId(IdGenerator.getId(service, Constants.TABLE_REGIONSTATISTICS,
						Constants.PREFIX_REGIONSTATISTICS, 10));
				model.setUserCre(getCurrentUser().getName());
				regionStaticService.save(model);
				ajaxDoneSuccess("保存成功");
			}else{
				model.setUserUpd(getCurrentUser().getName());
				regionStaticService.update(model);
				ajaxDoneSuccess("更新成功");
			}
		} catch (Exception e) {
			ajaxDoneSuccess("保存失败");
		}
	}
	/**
	 * 删除数据
	 * @throws Exception 
	 */
	public void delete() throws Exception{
		try {
			String[] idList=ids.split(",");
			regionStaticService.delete(idList);
			ajaxDoneSuccess("删除成功");
		} catch (Exception e) {
			ajaxDoneSuccess("删除失败");
		}
	}
	
	/**
	 * 获取数据列表
	 * @return
	 */
	public String getAllRecords(){
		//当前页  
		int intPage = Integer.parseInt((page == null || page == "0") ? "1":page);  
		//每页显示条数  
		int number = Integer.parseInt((rows == null || rows == "0") ? "5":rows);  
		//每页的开始记录  第一页为1  第二页为number +1   
		int start = (intPage-1)*number;

		Map<String, String> map=null;
		if(GlobalContext.RESULT_QUERY.equals(viewType)){ //如果执行查询操作
			map=new HashMap<String, String>();
			map.put("startDate", startDate);
			map.put("endDate",endDate);
			map.put("regionid", regionId);
		}

		int total=regionStaticService.getTotal(map);

		List<RegionStatistics> list=regionStaticService.getAllRecords(start, number, map);
		List<Map<String, Object>> maps=new ArrayList<Map<String,Object>>();
		for (RegionStatistics entity : list) {
			maps.add(entity.toMap());
		}
		Map<String, Object> json = new HashMap<String, Object>(); 
		json.put("total", total);
		json.put("rows", maps);
		resultObj =JSONObject.fromObject(json);
		
		return "success";
	}

	/**
	 * 获取统计图表数据
	 * @return
	 */
	public String getStatisticsData(){
		Map<String, String> map=null;
		if(GlobalContext.RESULT_QUERY.equals(viewType)){ //如果执行查询操作
			map=new HashMap<String, String>();
			map.put("startDate", startDate);
			map.put("endDate",endDate);
			map.put("regionid", regionId);
			viewType="";
		}
		List list=regionStaticService.getStatisticsData(map);
		if(list!=null && list.size()>0){
			statisObj=getJsonData(list);
		}
		
		return "statistics";
	}
	
	private JSONArray getJsonData(List list){
		List<List> result=new ArrayList<List>();
		List<Integer> tsList=new ArrayList<Integer>();
		List<Integer> mjList=new ArrayList<Integer>();
		List<Integer> jjList=new ArrayList<Integer>();
		
		for (int j = 0; j < 12; j++) {
			tsList.add(0);
			mjList.add(0);
			jjList.add(0);
		}
		
		for (int i = 0; i < list.size(); i++) {
			Object[] o=(Object[]) list.get(i);
			int index=(Integer) o[0]-1;
			tsList.add(index, DoubleToInt((Double) o[1]));
			mjList.add(index,DoubleToInt((Double)o[2]));
			jjList.add(index,DoubleToInt((Double)o[3]));
		}
		result.add(tsList);
		result.add(mjList);
		result.add(jjList);
		return JSONArray.fromObject(result);
	}
	
	private int DoubleToInt(Double d){
		String str=String.valueOf(d);
		String str1=str.substring(0,str.indexOf("."));
		return Integer.valueOf(str1);
	}
}
